package com.example.denglu.servlet;

import com.example.denglu.service.UserService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import javax.servlet.ServletException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String loginType = request.getParameter("type"); // username 或 phone
        response.setContentType("application/json;charset=utf-8");
        
        if ("username".equals(loginType)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            if (username == null || username.trim().isEmpty() || 
                password == null || password.trim().isEmpty()) {
                response.getWriter().write("{\"success\":false,\"message\":\"用户名和密码不能为空\"}");
                return;
            }
            
            boolean isSuccess = UserService.loginByUsername(username, password);
            if (isSuccess) {
                HttpSession session = request.getSession();
                session.setAttribute("isLoggedIn", true);
                session.setAttribute("username", username);
            }
            
            response.getWriter().write("{\"success\":" + isSuccess + 
                    ",\"message\":\"" + (isSuccess ? "登录成功" : "用户名或密码错误") + "\"}");
            
        } else if ("phone".equals(loginType)) {
            String phone = request.getParameter("phone");
            String code = request.getParameter("code");
            
            if (phone == null || phone.trim().isEmpty() || 
                code == null || code.trim().isEmpty()) {
                response.getWriter().write("{\"success\":false,\"message\":\"手机号和验证码不能为空\"}");
                return;
            }
            
            // 验证验证码
            HttpSession session = request.getSession();
            String savedCode = (String) session.getAttribute(phone + "_code");
            System.out.println("验证码比对 - 手机号：" + phone);
            System.out.println("验证码比对 - 用户输入：" + code);
            System.out.println("验证码比对 - 存储的值：" + savedCode);
            
            if (savedCode == null) {
                response.getWriter().write("{\"success\":false,\"message\":\"验证码已过期，请重新获取\"}");
                return;
            }
            
            if (!savedCode.equals(code)) {
                response.getWriter().write("{\"success\":false,\"message\":\"验证码错误\"}");
                return;
            }
            
            // 检查手机号是否已注册
            boolean isRegistered = UserService.isPhoneRegistered(phone);
            
            // 设置session
            session.setAttribute("isLoggedIn", true);
            session.setAttribute("phone", phone);
            session.removeAttribute(phone + "_code");
            
            if (!isRegistered) {
                // 未注册用户
                if (!UserService.createTempUser(phone)) {
                    response.getWriter().write("{\"success\":false,\"message\":\"系统错误\"}");
                    return;
                }
                // 返回需要设置密码的标志
                response.getWriter().write(
                    "{\"success\":true,\"needSetPassword\":true,\"redirectUrl\":\"set-password.html\"," +
                    "\"message\":\"验证成功，请设置密码\"}"
                );
            } else {
                // 已注册用户，检查是否需要设置密码
                boolean needSetPassword = UserService.needSetPassword(phone);
                if (needSetPassword) {
                    response.getWriter().write(
                        "{\"success\":true,\"needSetPassword\":true,\"redirectUrl\":\"set-password.html\"," +
                        "\"message\":\"登录成功，请设置密码\"}"
                    );
                } else {
                    response.getWriter().write(
                        "{\"success\":true,\"needSetPassword\":false,\"redirectUrl\":\"game-home.html\"," +
                        "\"message\":\"登录成功\"}"
                    );
                }
            }
            
        } else {
            response.getWriter().write("{\"success\":false,\"message\":\"无效的登录类型\"}");
        }
    }
} 